package com.houseliker.activity.calculate;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.houseliker.Constants;
import com.houseliker.R;
import com.houseliker.activity.BaseActivity;
import com.houseliker.adapter.calculate.RateAdapter;
import com.houseliker.model.Rate;
import com.houseliker.model.Result;
import com.houseliker.net.HttpApi.JsonHttpApi;
import com.houseliker.net.HttpApi.MapHttpApi;
import com.houseliker.net.HttpApi.bean.Response;
import com.houseliker.net.ThreadTask.JsonThreadTask;
import com.houseliker.net.ThreadTask.MapThreadTask;
import com.houseliker.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 只展示5年以上的商业贷款business下的e是5年以上的d(3-5年)c(1-3年)
 * 只展示5年以上的公积金贷款gjj下的e是5年以上d(1-5年)
 * Created by sunrx on 2015/12/10.
 */
public class SelectRateActivity extends BaseActivity {

    private ListView lv_rate;
    private EditText et_rate;
    private List<Rate.RateValue> businessList;
    private String from;//business,gjj
    private int years;

    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_rate, TYPE_HEADER);
        setHeaderBar("选择利率", "确定");

        sharedPreferences = getSharedPreferences(Constants.SP_RATE, MODE_PRIVATE);
        from = getIntent().getStringExtra("from");
        years = getIntent().getIntExtra("years", 20);

        initViews();

        registListener();

        new GetRateList().execute();
        new GetUpdate1().execute();
    }

    private void registListener() {
        lv_rate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != businessList.get(position)) {
                    Intent intent = new Intent();
                    intent.putExtra("rateValue", businessList.get(position).value);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });

        et_rate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                if (temp.startsWith(".")) {
                    s.delete(0, 1);
                }
                int posDot = temp.indexOf(".");
                if (posDot <= 0) {
                    if (temp.length() <= 2) {
                        return;
                    } else {
                        s.delete(2, 3);
                        return;
                    }
                }
                if (temp.length() - posDot - 1 > 2) {
                    s.delete(posDot + 3, posDot + 4);
                }
            }
        });
    }

    private class GetRateList extends MapThreadTask {

        @Override
        protected Map<String, String> onPreExecute() {
            Map<String, String> params = new HashMap<String, String>();
            return params;
        }

        @Override
        protected Response doInBackground(Map<String, String> params) {
            Log.i("Thread", Thread.currentThread().getName() + " # " + Thread.currentThread().getId());
            String url = "http://house.ifeng.com/finance/calc/test";
            return new MapHttpApi(url,params).POST();
        }

        @Override
        protected void onPostExecute(Response response) {
            Log.i("onPostExecute", "onPostExecute" + response);
            super.onPostExecute(response);
            Result<Rate> result = gson.fromJson(response.result, new TypeToken<Result<Rate>>() {
            }.getType());
            if (null != result && null != result.data) {
                Rate rate = result.data;
                if (null != rate.l) {
                    if ("business".equals(from) && null != rate.l.get("business")) {
                        if (years <= 3) {
                            //商业贷款一到三年
                            businessList = rate.l.get("business").get("c");
                        } else if (3 < years && years <= 5) {
                            //商业贷款三到五年
                            businessList = rate.l.get("business").get("d");
                        } else {
                            //商业贷款五年以上
                            businessList = rate.l.get("business").get("e");
                        }

                        if (null != businessList && businessList.size() > 0) {
                            RateAdapter rateAdapter = new RateAdapter(mContext, businessList);
                            lv_rate.setAdapter(rateAdapter);
                        }
                    } else if ("gjj".equals(from) && null != rate.l.get("gjj")) {
                        if (years <= 5) {
                            //公积金贷款一到五年
                            businessList = rate.l.get("gjj").get("d");
                        } else {
                            //公积金贷款五年以上
                            businessList = rate.l.get("gjj").get("e");
                        }
                        if (null != businessList && businessList.size() > 0) {
                            RateAdapter rateAdapter = new RateAdapter(mContext, businessList);
                            lv_rate.setAdapter(rateAdapter);
                        }
                    }
                    //保存利率
                    try {
                        //公积金
                        String GJJ_RATE_1_5 = rate.l.get("gjj").get("d").get(0).value;
                        String GJJ_RATE_5 = rate.l.get("gjj").get("e").get(0).value;
                        //商业
                        String SY_RATE_1_3 = rate.l.get("business").get("c").get(0).value;
                        String SY_RATE_3_5 = rate.l.get("business").get("d").get(0).value;
                        String SY_RATE_5 = rate.l.get("business").get("e").get(0).value;
                        //
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("GJJ_RATE_1_5", GJJ_RATE_1_5);
                        editor.putString("GJJ_RATE_5", GJJ_RATE_5);
                        editor.putString("SY_RATE_1_3", SY_RATE_1_3);
                        editor.putString("SY_RATE_3_5", SY_RATE_3_5);
                        editor.putString("SY_RATE_5", SY_RATE_5);
                        editor.commit();
                    } catch (Exception e) {
                        Log.e("Saving rate of interest", e.toString());
                    }
                }
            }
        }
    }

    private class GetUpdate1 extends JsonThreadTask {

        @Override
        protected String onPreExecute() {
            String params = null;
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("age", 10);
                jsonObject.put("name", "racine");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            params = jsonObject.toString();
            return params;
        }

        @Override
        protected Response doInBackground(String params) {
            Log.i("Thread", Thread.currentThread().getName() + " # " + Thread.currentThread().getId());
            String url = "http://172.28.12.6:8080/app";
            return new JsonHttpApi(url, params).POST();
        }

        @Override
        protected void onPostExecute(Response response) {
            Log.i("onPostExecute", "#" + response);
        }
    }

    @Override
    protected void onLeftButtonClick() {
        super.onLeftButtonClick();
        finish();
    }

    @Override
    protected void onRightButtonClick() {
        super.onRightButtonClick();
        String customRate = et_rate.getText().toString().trim();

        if (StringUtils.isNullOrEmpty(customRate)) {
            C_Toast("请您输入利率!");
        } else {
            if (StringUtils.canParseFloat(customRate)) {
                Float rate = Float.valueOf(customRate);
                if (0 == rate) {
                    C_Toast("请您输入大于0小于100的数值!");
                    return;
                }
            }
            Intent intent = new Intent();
            intent.putExtra("rateValue", customRate);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private void initViews() {
        lv_rate = (ListView) findViewById(R.id.lv_rate);
        et_rate = (EditText) findViewById(R.id.et_rate);
    }
}
